package com.thinkgem.jeesite.common.utils;
import java.beans.PropertyDescriptor;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.log4j.Logger;

import net.sf.json.JSONObject;



/**
 * 常用工具类
 * @author zahngyangze
 *
 */
public class ToolsUtil {
	private static Logger log = Logger.getLogger(ToolsUtil.class);
	
	
	/** 自定义进制(0,1没有加入,容易与o,l混淆) */
	private static final char[] r = new char[] { 'Q', 'w', 'E', '8', 'a', 'S', '2', 'd', 'Z', 'x', '9', 'c', '7', 'p', 'O', '5', 'i', 'K', '3', 'm', 'j', 'U', 'f', 'r', '4', 'V', 'y', 'L', 't', 'N',
			'6', 'b', 'g', 'H' };
	/** 自动补全组(不能与自定义进制有重复) */
	private static final char[] b = new char[] { 'q', 'W', 'e', 'A', 's', 'D', 'z', 'X', 'C', 'P', 'o', 'I', 'k', 'M', 'J', 'u', 'F', 'R', 'v', 'Y', 'T', 'n', 'B', 'G', 'h' };
	/** 进制长度 */
	private static final int l = r.length;
	/** 序列最小长度 */
	private static final int s = 6;
	
	
	
    
    /**
     * String转Integer
     * 
     * @param str
     * @return 返回Integer
     */
    public static Integer strToInt(String str) {
        Integer result = 0;
        try {
            result = Integer.parseInt(str);
        } catch (Exception ex) {
            log.error(ex);
            ex.printStackTrace();
        }
        return result;
    }
    
    /**
	 * 验证是否为手机号
	 * 
	 * @param tel
	 * @return
	 */
	public static boolean isTel(String tel) {
		String regex = "1[3|4|5|7|8|][0-9]{9}";
		return match(regex, tel);
	}
	
	/**
	 * @param regex
	 *            正则表达式字符串
	 * @param str
	 *            要匹配的字符串
	 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
	 */
	public static boolean match(String regex, String str) {
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str);
		return matcher.matches();
	}

    
    /**
     * String[]数组转List
     * 
     * @param str
     * @return 返回List
     */
    public static List<String> strToList(String str) {
        List<String> list = new ArrayList<String>();
        if(str.indexOf(",") > 0){
            String[] dates = str.split(",");
            list = Arrays.asList(dates);
        }                
        return list;
    }
    
    /**
     * String转char
     * 
     * @param str
     * @return 返回char值
     */
    public static char strToChar(String str) {
        int tmp = strToInt(str);
        return (char) (tmp + '0');
    }
    
    /**
     * double转int
     * 
     * @param dou
     * @return 返回int值
     */
    public static int doubleToInt(double dou) {
        int result = 0;
        try {
            result = (int) dou;
        } catch (Exception ex) {
            log.error(ex);
            ex.printStackTrace();
        }
        return result;
    }
    
    /**
     * 日期转格式化字符串
     * 
     * @param date
     *            日期
     * @param formate
     *            格式字符串
     * @return 格式化后日期
     * @throws ParseException 
     */
    public static String dateFormate(Date date, String formate) { 
        try{
            if (date == null) {
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                date = format.parse("1970-01-01 00:00:00");
            }              
        }catch(ParseException pex){
            log.error(pex);
            pex.printStackTrace();
        }
        DateFormat dateFormat = new SimpleDateFormat(formate);
        return dateFormat.format(date); 
    }
    
    /**
     * 日期转格式化字符串(yyyy-MM-dd)
     * 
     * @param date
     *            日期
     * @return 格式化后日期"yyyy-MM-dd"
     */
    public static String dateFormate(Date date) {
        return dateFormate(date, "yyyy-MM-dd");
    }
    
    /**
     * 日期转格式化字符串(yyyy/MM/dd)
     * 
     * @param date
     *            日期
     * @return 格式化后日期"yyyy/MM/dd"
     */
    public static String dateFormateSlash(Date date) {
        return dateFormate(date, "yyyy/MM/dd");
    }
    
    /**
     * 日期转格式化字符串(yyyy/MM/dd HH:mm)
     * 
     * @param date
     *            日期
     * @return 格式化后日期"yyyy/MM/dd HH:mm"
     */
    public static String dateTimeFormateSlash(Date date) {
        return dateFormate(date, "yyyy/MM/dd HH:mm");
    }
    
    /**
     * 日期转格式化字符串(yyyy/MM/dd HH:mm:ss)
     * 
     * @param date
     *            日期
     * @return 格式化后日期"yyyy/MM/dd HH:mm:ss"
     */
    public static String dateTimeFormateSlashSecond(Date date) {
        return dateFormate(date, "yyyy/MM/dd HH:mm:ss");
    }
    
    /**
     * 日期转格式化字符串(MM/dd HH:mm)
     * 
     * @param date
     *            日期
     * @return 格式化后日期"MM/dd HH:mm"
     */
    public static String dateTimeFormateSlashNoYear(Date date) {
        return dateFormate(date, "MM/dd HH:mm");
    }
    
    /**
     * 日期转时间格式化字符串(HH:mm)
     * 
     * @param date
     *            日期
     * @return 格式化后时间"HH:mm"
     */
    public static String timeFormate(Date date) {
        return dateFormate(date, "HH:mm");
    }
    
    /**
     * 字符串转Date
     * @param timeStr 时间字符串
     * @param formate 格式化形式
     * @return
     * @throws ParseException
     */
    public static Date strToDate(String timeStr,String formate) throws ParseException{
    	if(!isTrue(timeStr)){
    		timeStr = "1970-01-01 00:00:00";
    	}
    	if(!isTrue(formate)){
    		formate = "yyyy-MM-dd HH:mm:ss";
    	}
    	SimpleDateFormat sdf = new SimpleDateFormat(formate);
    	Date date = sdf.parse(timeStr);
    	return date;
    	
    }
    
    /**
     * 字符串转布尔值
     * 
     * @param str
     *            "1"是true,其他是false
     * @return 转换后的布尔值
     */
    public static Boolean strToBool(String str) {
        if ("1".equals(str)) {
            return true;
        } else {
            return false;
        }
    }   
    
    /**
     * 字符串转整型数组
     * 
     * @param str 字符串
     * @return 返回整型数组
     */
    public static Integer[] strToIntArray(String str){
        Integer[] ints = null;
        if(str.indexOf(",") > 0){
            String[] dates = str.split(",");
            ints = new Integer[dates.length];
            for(int i = 0; i < dates.length; i++){
                ints[i] = strToInt(dates[i]);
            }
        } 
        return ints;
    }
    
    public static String[] strToStrArray(String str){
    	String[] strs = null;
    	if(!isTrue(str)){
    		strs = new String[1];
    	}else{
    		if(str.indexOf(",") > 0){
                String[] dates = str.split(",");
                strs = new String[dates.length];
                for(int i = 0; i < dates.length; i++){
                	if(isTrue(strs[i])){
                		strs[i] = dates[i];
                	}else{
                		break;
                	}
                }
            }else{
            	if(isTrue(str)){
            		 strs = new String[1];
            		 strs[0] = str;
            	}
            }
    	}
        return strs;
    }
    
    /**
     * 保留小数点后两位
     * @param var  传入的双整型
     * @return 返回处理结果
     */
    public static BigDecimal keepTwoDecimal(BigDecimal var){
        BigDecimal result = new BigDecimal(0.00);
        if(var != null){
            result = var.setScale(2,BigDecimal.ROUND_HALF_UP);
        }
        return result;
    }
    
    /**
     * 判断字符串是否不为空
     * @param msg
     * @return
     */
    public static boolean isTrue(Object msg){
    	if(msg != null && !"".equals(msg)){
    		return true;
    	}
    	return false;
    }
    
    /**
	 * 根据ID生成六位随机码
	 * 
	 * @param num
	 *            ID
	 * @return 随机码
	 */
	public static String toSerialNumber(long num) {
		char[] buf = new char[32];
		int charPos = 32;

		while ((num / l) > 0) {
			buf[--charPos] = r[(int) (num % l)];
			num /= l;
		}
		buf[--charPos] = r[(int) (num % l)];
		String str = new String(buf, charPos, (32 - charPos));
		// 不够长度的自动随机补全
		if (str.length() < s) {
			StringBuffer sb = new StringBuffer();
			Random rnd = new Random();
			for (int i = 0; i < s - str.length(); i++) {
				sb.append(b[rnd.nextInt(24)]);
			}
			str += sb.toString();
		}
		return str;
	}
	
	
	/**
	 * 获取一个6位的验证码
	 * @return
	 */
	public static String getValidateCode(){
		Random r = new Random();
		String validateCode = "";
		for (int i = 0; i < 6; i++) {
			int num = r.nextInt(10);
			validateCode+=num;
		}
		return validateCode;
	}
	public static String getValidateCode4(){
		Random r = new Random();
		String validateCode = "";
		for (int i = 0; i < 4; i++) {
			int num = r.nextInt(10);
			validateCode+=num;
		}
		return validateCode;
	}
	
	
	 /**
	* @Description 将字符串中的emoji表情转换成可以在utf-8字符集数据库中保存的格式（表情占4个字节，需要utf8mb4字符集）
	* @param str
	* 待转换字符串
	* @return 转换后字符串
	* @throws UnsupportedEncodingException
	* exception
	*/
	public static String emojiConvert1(String str)
	throws UnsupportedEncodingException {
		String patternString = "([\\x{10000}-\\x{10ffff}])";//\ud800-\udfff
	
		Pattern pattern = Pattern.compile(patternString);
		Matcher matcher = pattern.matcher(str);
		StringBuffer sb = new StringBuffer();
		while(matcher.find()) {
			try {
				matcher.appendReplacement(
				sb,
				"[["
				+ URLEncoder.encode(matcher.group(1),
				"UTF-8") + "]]");
			} catch(UnsupportedEncodingException e) {
				e.printStackTrace();
				log.error("emojiConvert error", e);
				throw e;
			}
		}
		matcher.appendTail(sb);
			log.debug("emojiConvert " + str + " to " + sb.toString()
					+ ", len：" + sb.length());
		return sb.toString();
	}

	/**
	* @Description 还原utf8数据库中保存的含转换后emoji表情的字符串
	* @param str
	* 转换后的字符串
	* @return 转换前的字符串
	* @throws UnsupportedEncodingException
	* exception
	*/
	public static String emojiRecovery2(String str)
	throws UnsupportedEncodingException {
		String patternString = "\\[\\[(.*?)\\]\\]";
	
		Pattern pattern = Pattern.compile(patternString);
		Matcher matcher = pattern.matcher(str);
	
		StringBuffer sb = new StringBuffer();
		while(matcher.find()) {
			try {
				matcher.appendReplacement(sb,
				URLDecoder.decode(matcher.group(1), "UTF-8"));
			} catch(UnsupportedEncodingException e) {
				e.printStackTrace();
				log.error("emojiRecovery error", e);
				throw e;
			}
		}
		matcher.appendTail(sb);
		log.debug("emojiRecovery " + str + " to " + sb.toString());
		return sb.toString();
	}
	
	/**
	 * 实体类转Map
	 * @param obj
	 * @return
	 */
	public static Map<String, Object> beanToMap(Object obj) { 
        Map<String, Object> params = new HashMap<String, Object>(0); 
        try { 
            PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean(); 
            PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj); 
            for (int i = 0; i < descriptors.length; i++) { 
                String name = descriptors[i].getName(); 
                if (!"class".equals(name)) { 
                	String key = name.toUpperCase();
                	Object value = propertyUtilsBean.getNestedProperty(obj, name);
                	if(value==null || "".equals(value)){
                		params.put(key,"" ); 
                	}else{
                		params.put(key,value ); 
                	}
                } 
            } 
        } catch (Exception e) { 
        	log.debug("bean " + obj + " to  map");
            e.printStackTrace(); 
        } 
        return params; 
}
	
	
public static JSONObject objectToJson(Object obj){
	JSONObject jSONObject =JSONObject.fromObject(obj);
	System.out.println(jSONObject);
		return jSONObject;
	}
	
	/**
	 * Java文件操作 获取文件扩展名
	 *
	 *  Created on: 2011-8-2
	 */
    public static String getExtensionName(String filename) { 
        if ((filename != null) && (filename.length() > 0)) { 
            int dot = filename.lastIndexOf('.'); 
            if ((dot >-1) && (dot < (filename.length() - 1))) { 
                return filename.substring(dot + 1); 
            } 
        } 
        return filename; 
    }

	public static void main(String[] args) {
		//FindCarApplyToConfirmInfo f = new FindCarApplyToConfirmInfo();
		// Map<String, Object> p = beanToMap(f);
//		 System.out.println(p);
	}
	
	
}
